import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

/// 本地存储
class StorageUtil {
  static StorageUtil _instance = StorageUtil._();

  factory StorageUtil() => _instance;

  StorageUtil._();

  static Future<void> init() async {
    _pref = await SharedPreferences.getInstance();
  }

  static late SharedPreferences _pref;

  /// 设置 json 对象
  Future<bool> setJson(String key, dynamic jsonVal) {
    String jsonString = jsonEncode(jsonVal);
    return _pref.setString(key, jsonString);
  }

  /// 获取 json 对象
  dynamic getJson(String key) {
    String? jsonString = _pref.getString(key);
    return jsonString == null ? null : jsonDecode(jsonString);
  }


  Future<bool> setBool(String key, bool val) {
    return _pref.setBool(key, val);
  }

  bool getBool(String key) {
    bool? val = _pref.getBool(key);
    return val == null ? false : val;
  }


  /// 删除 json 对象
  Future<bool> remove(String key) {
    return _pref.remove(key);
  }
}
